package com.uinnova.product.eam.web.bm.mvc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.util.ControllerUtils;
import com.binary.framework.web.RemoteResult;
import com.uinnova.product.eam.base.local.TaskFromWorkflowContext;
import com.uinnova.product.eam.base.local.TaskFromWorkflowContextValue;
import com.uinnova.product.eam.db.bean.DiagramChangeData;
import com.uinnova.product.eam.model.asset.EamCiRltDTO;
import com.uinnova.product.eam.model.asset.EamDiagramHistoryInfo;
import com.uinnova.product.eam.model.asset.EamReleaseHistoryDTO;
import com.uinnova.product.eam.model.bm.EamClassDesc;
import com.uinnova.product.eam.model.bm.QuickDrawingDto;
import com.uinnova.product.eam.model.bm.QuickDrawingResp;
import com.uinnova.product.eam.model.bm.ReleaseValidResponse;
import com.uinnova.product.eam.model.vo.CheckBatchArtifactRuleVo;
import com.uinnova.product.eam.web.bm.bean.ReleaseDiagramReq;
import com.uinnova.product.eam.web.bm.bean.ReleaseModuleDiagramDTO;
import com.uinnova.product.eam.web.bm.peer.BmDiagramPeer;
import com.uinnova.product.vmdb.comm.bean.QueryPageCondition;
import com.uinnova.product.vmdb.comm.doc.annotation.ModDesc;
import com.uinnova.product.vmdb.comm.doc.annotation.MvcDesc;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CiGroupPage;
import com.uinnova.product.vmdb.provider.rlt.bean.CcCiRltInfo;
import com.uinnova.project.base.diagram.comm.diagram.ESDiagramMoveCdt;
import com.uinnova.project.base.diagram.comm.model.ESDiagramDTO;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.query.ESCISearchBean;
import com.uino.bean.permission.base.SysUser;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 业务建模视图处理相关接口
 *
 * @author ch
 * @date 2021/11/3
 */
@Slf4j
@RestController
@RequestMapping("/bm/diagram")
@MvcDesc(author = "ch", desc = "业务建模视图处理相关接口")
public class BmDiagramMvc {

    @Resource
    private BmDiagramPeer bmDiagramPeer;

    @PostMapping("/handlerRelease")
    @ResponseBody
    @ModDesc(desc = "判断发布的版本", pDesc = "", rDesc = "处理结果", rType = RemoteResult.class)
    public RemoteResult handlerRelease(@RequestBody String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        String diagramId = jsonObject.getString("diagramId");
        boolean result = bmDiagramPeer.handlerRelease(diagramId);
        return new RemoteResult(result);
    }

    @PostMapping("/cancelTips")
    @ModDesc(desc = "弹出框不再提示", pDesc = "", rDesc = "弹出框不再提示", rType = RemoteResult.class)
    public RemoteResult cancelTips(@RequestBody String body) {
        JSONObject paramJson = JSON.parseObject(body);
        String viewType = paramJson.getString("viewType");
        SysUser currentUser = SysUtil.getCurrentUserInfo();
        boolean result = bmDiagramPeer.cancelTips(viewType, currentUser.getId());
        return new RemoteResult(result);
    }

    @PostMapping("/getTipsStatus")
    @ModDesc(desc = "获取弹出框状态", pDesc = "", rDesc = "获取弹出框状态", rType = RemoteResult.class)
    public RemoteResult getTipsStatus(@RequestBody String body) {
        JSONObject paramJson = JSON.parseObject(body);
        String viewType = paramJson.getString("viewType");
        SysUser currentUser = SysUtil.getCurrentUserInfo();
        boolean result = bmDiagramPeer.getTipsStatus(viewType, currentUser.getId());
        return new RemoteResult(result);
    }

    @PostMapping("/queryReleaseHistory")
    @ModDesc(desc = "查询业务建模资产视图发布历史信息", pDesc = "", rDesc = "历史版本信息", rType = RemoteResult.class)
    public RemoteResult queryReleaseHistory(@RequestBody String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        String id = jsonObject.getString("id");
        Boolean historyFlag = jsonObject.getBoolean("historyFlag");
        if(BinaryUtils.isEmpty(historyFlag)){
            historyFlag = false;
        }
        // List<EamReleaseHistoryDTO> result = bmDiagramPeer.queryReleaseHistory(id, historyFlag);
        List<EamDiagramHistoryInfo> result = JSONObject.parseArray(JSONObject.toJSONString(bmDiagramPeer.queryReleaseHistory(id, historyFlag)), EamDiagramHistoryInfo.class);
        return new RemoteResult(result);
    }

    @PostMapping("/isCheckOScanning")
    @ModDesc(desc = "视图数据检核", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult isCheckOScanning(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = false) ReleaseModuleDiagramDTO diagramDTO) {
        List<String> diagramIds = new ArrayList<>();
        if (!BinaryUtils.isEmpty(diagramDTO.getDiagramId())) {
            diagramIds.add(diagramDTO.getDiagramId());
        }
        if (!CollectionUtils.isEmpty(diagramDTO.getDiagramIds())) {
            diagramIds.addAll(diagramDTO.getDiagramIds());
        }
        List<DiagramChangeData> names = bmDiagramPeer.isCheckOScanning(diagramIds);
        return new RemoteResult(names);
    }


    @PostMapping("/getChangeCIDataByDEnergyId")
    @ModDesc(desc = "根据视图加密ID获取视图变更数据", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult getChangeCIDataByDEnergyId(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, List<DiagramChangeData>> data = bmDiagramPeer.getChangeCIDataByDEnergyId(diagramDTO.getDiagramId());
        return new RemoteResult(data);
    }

    @PostMapping("/publishDiagram")
    @ModDesc(desc = "视图发布接口", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult publishDiagram(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        TaskFromWorkflowContext.setContext(new TaskFromWorkflowContextValue(false, SysUtil.getCurrentUserInfo().getLoginCode()));
        String id = bmDiagramPeer.publishDiagram(diagramDTO.getDiagramId(), diagramDTO.getReleaseDesc(), diagramDTO.getDirId(), diagramDTO.getReleaseDiagramId());
        TaskFromWorkflowContext.release();
        return new RemoteResult(id);
    }

    @PostMapping("/getVersionChangeCIByDEnergyId")
    @ModDesc(desc = "获取视图版本更新的变更数据对比", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult getVersionChangeCIByDEnergyId(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Boolean isLastestVersion = bmDiagramPeer.getVersionChangeCIByDEnergyId(diagramDTO.getDiagramId());
        return new RemoteResult(isLastestVersion);
    }

    @PostMapping("/freshBindingEleByDEnergyId")
    @ModDesc(desc = "重新绑定视图需要检出的要素", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult freshBindingEleByDEnergyId(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Boolean data = bmDiagramPeer.freshBindingEleByDEnergyId(diagramDTO.getDiagramId(), diagramDTO.getNames(), diagramDTO.getReleaseDiagramId(), diagramDTO.getDiagramIds());
        return new RemoteResult(data);
    }

    @PostMapping("/getVersionChangeDiagramByDEnergyId")
    @ModDesc(desc = "确认视图版本更新接口 支持批量", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult getVersionChangeDiagramByDEnergyId(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, Boolean> isLastestVersion = bmDiagramPeer.getVersionChangeDiagramByDEnergyId(diagramDTO.getDiagramIds());
        return new RemoteResult(isLastestVersion);
    }

    @PostMapping("/pushBeforeCheckView")
    @ModDesc(desc = "发布视图前校验视图信息", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult pushBeforeCheckView(@Valid @RequestBody ReleaseDiagramReq params) {
        ReleaseValidResponse response = bmDiagramPeer.pushBeforeCheckView(params.getCatalogueIds());
        return new RemoteResult(response);
    }

    @PostMapping("checkModelComplete")
    @ModDesc(desc = "模型完整性校验", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public void checkModelComplete(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseDiagramReq params) {
        String result = bmDiagramPeer.checkModelComplete(params);
        ControllerUtils.returnJson(request, response, result);
    }

    @PostMapping("/categoryEleNumCheck")
    @ModDesc(desc = "视图制品数量校验接口", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult categoryEleNumCheck(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        List<String> msgList = bmDiagramPeer.categoryEleNumCheck(diagramDTO.getDiagramId(), diagramDTO.getViewType());
        return new RemoteResult(msgList);
    }

    @PostMapping("/categoryEleNumCheckBatch")
    @ModDesc(desc = "视图制品数量校验接口 批量", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult categoryEleNumCheckBatch(@RequestBody List<String> diagramIds) {
        List<CheckBatchArtifactRuleVo> msgList = bmDiagramPeer.categoryEleNumCheckBatch(diagramIds);
        return new RemoteResult(msgList);
    }

    @PostMapping("/freshPublishDiagramAttr")
    @ModDesc(desc = "刷新发布视图的releaseDiagramId字段", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult freshPublishDiagramAttr(HttpServletRequest request, HttpServletResponse response) {
        Integer result = bmDiagramPeer.freshPublishDiagramAttr();
        return new RemoteResult(result);
    }

    @PostMapping("/extCheckAttrByDiagramId")
    @ModDesc(desc = "视图发布 图外根据视图id校验视图内资产必填项  （支持批量）", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult extCheckAttrsByDiagramIds(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, Map<String, String>> result = bmDiagramPeer.extCheckAttrByDiagramIds(diagramDTO.getDiagramIds());
        return new RemoteResult(result);
    }

    @PostMapping("/batchCategoryEleNumCheck")
    @ModDesc(desc = "视图发布 图外根据视图id批量校验视图实例个数", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult batchCategoryEleNumCheck(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, List<String>> result = bmDiagramPeer.batchCategoryEleNumCheck(diagramDTO.getDiagramIds());
        return new RemoteResult(result);
    }

    @PostMapping("/batchPublishDiagram")
    @ModDesc(desc = "视图发布 视图", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult batchPublishDiagram(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, String> result = bmDiagramPeer.batchPublishDiagram(diagramDTO);
        return new RemoteResult(result);
    }

    @PostMapping("getActivityListByTaskRlt")
    public RemoteResult getActivityListByTaskRlt(@RequestBody String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        String diagramId = jsonObject.getString("diagramId");
        String ciCode = jsonObject.getString("ciCode");
        String libType = jsonObject.getString("libType");
        List<CcCiRltInfo> rltInfoList= bmDiagramPeer.getActivityListByTaskRlt(diagramId, ciCode, libType);
        return new RemoteResult(rltInfoList);
    }

    @PostMapping("/refreshPrepareDiagramId")
    @ModDesc(desc = "刷新伏羲本地视图 prepareDiagramId 字段", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult refreshPrepareDiagramId(HttpServletRequest request, HttpServletResponse response) {
        Boolean res = bmDiagramPeer.refreshPrepareDiagramId();
        return new RemoteResult(res);
    }

    @PostMapping("/checkSpikPage")
    @ModDesc(desc = "校验视图跳转页面 可编辑 - studio ：不可编辑 - lookUp ： 不能查看 - no", pDesc = "", rDesc = "", rType = RemoteResult.class)
    public RemoteResult checkSpikPage(HttpServletRequest request, HttpServletResponse response, @RequestBody List<ReleaseModuleDiagramDTO> diagramDTOS) {
        Map<String, Long> prepareAndType = new HashMap<>();
        diagramDTOS.forEach(e -> {
            prepareAndType.put(e.getPrepareId(), e.getDirType());
        });
        Map<String, ESDiagramMoveCdt> res = bmDiagramPeer.checkSpikPage(prepareAndType);
        return new RemoteResult(res);
    }

    @RequestMapping("/queryCiInfoModuleBySearchBean")
    @Deprecated
    @ModDesc(desc = "组件建模-分页查询对象数据-过滤设计库不存在对象", pDesc = "条件查询", pType = QueryPageCondition.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = CiGroupPage.class)
    public void queryCiInfoModuleBySearchBean(@RequestParam(defaultValue = "PRIVATE") LibType libType,
                                        HttpServletRequest request, HttpServletResponse response, @RequestBody ESCISearchBean bean) {

        CiGroupPage result = bmDiagramPeer.queryCiInfoModuleBySearchBean(bean, libType);
        ControllerUtils.returnJson(request, response, result);
    }

    @RequestMapping("/existCheckData")
    @ModDesc(desc = "视图检出前校验 - 本地是否存在与设计库关联视图", pDesc = "条件查询", pType = QueryPageCondition.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = CiGroupPage.class)
    public RemoteResult existCheckData(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, Object> result = bmDiagramPeer.existCheckData(diagramDTO.getDiagramId(), diagramDTO.getDirId());
        return new RemoteResult(result);
    }

    @RequestMapping("/existCheckConflict")
    @ModDesc(desc = "视图检出前校验 - 设计库视图与本地视图是否存在版本冲突", pDesc = "条件查询", pType = QueryPageCondition.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = CiGroupPage.class)
    public RemoteResult existCheckConflict(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        List<DiagramChangeData> names = bmDiagramPeer.existCheckConflict(diagramDTO.getDiagramId());
        return new RemoteResult(names);
    }

    @RequestMapping("/generalCheckOutDiagram")
    @ModDesc(desc = "视图检出", pDesc = "条件查询", pType = QueryPageCondition.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = CiGroupPage.class)
    public RemoteResult generalCheckOutDiagram(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        String id = bmDiagramPeer.generalCheckOutDiagram(diagramDTO.getDiagramId(), diagramDTO.getDirId(), diagramDTO.getActionType(), diagramDTO.getDiagramName());
        return new RemoteResult(id);
    }

    @RequestMapping("/queryClassDesc")
    @ModDesc(desc = "根据制品查询分类提示信息", pDesc = "制品id", pType = String.class, rDesc = "提示信息", rType = CiGroupPage.class)
    public RemoteResult queryClassDesc(@RequestBody String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        Long id = jsonObject.getLong("id");
        List<EamClassDesc> result = bmDiagramPeer.queryClassDesc(id);
        return new RemoteResult(result);
    }

    @RequestMapping("/quickDrawing")
    @ModDesc(desc = "自动成图", pDesc = "条件", pType = QuickDrawingDto.class, rDesc = "对象数据", rType = QuickDrawingResp.class)
    public RemoteResult quickDrawing(@RequestBody QuickDrawingDto drawingDto) {
        QuickDrawingResp result = bmDiagramPeer.quickDrawing(drawingDto);
        return new RemoteResult(result);
    }

    @RequestMapping("/queryDiagramInfoByIdAndVersion")
    @ModDesc(desc = "根据视图ID和VERSION查询对应的试图版本数据", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult queryDiagramInfoByIdAndVersion(@RequestBody List<ReleaseModuleDiagramDTO> diagramDTOS) {
        Map<String, ESDiagramDTO> result = bmDiagramPeer.queryDiagramInfoByIdAndVersion(diagramDTOS);
        return new RemoteResult(result);
    }

    @RequestMapping("/getVersionChangeByDEnergyId")
    @ModDesc(desc = "根据视图ID校验视图CI版本以及视图本身版本（融合之前的两个接口）", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult getVersionChangeByDEnergyId(HttpServletRequest request, HttpServletResponse response, @RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, Boolean> isLastestVersion = bmDiagramPeer.getVersionChangeByDEnergyId(diagramDTO.getDiagramIds());
        return new RemoteResult(isLastestVersion);
    }

    @RequestMapping("/checkDiagramConflictByDIds")
    @ModDesc(desc = "批量校验视图内容冲突（主键，制品数量，CI必填项，视图版本，CI版本）", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult checkDiagramConflictByDIds(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Map<Integer, Object> result = bmDiagramPeer.checkDiagramConflictByDIds(diagramDTO.getDiagramIds());
        return new RemoteResult(result);
    }

    @RequestMapping("/freshConflectData")
    @ModDesc(desc = "根据业务主键将刷新用户私有库冲突数据刷新为设计库数据", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult freshConflectData(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        Boolean data = bmDiagramPeer.freshConflectData(diagramDTO.getCiPrimaryKeys(), diagramDTO.getOwnerCode());
        return new RemoteResult(data);
    }

    @RequestMapping("/getHistroyCIInfoByDiagramId")
    @ModDesc(desc = "根据视图历史版本ID查询CI数据", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult getHistroyCIInfoByDiagramId(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        List<CcCiInfo> data = bmDiagramPeer.getHistroyCIInfoByDiagramId(diagramDTO.getDiagramId(), diagramDTO.getSheetId());
        return new RemoteResult(data);
    }

    @RequestMapping("/getHistroyCIInfoByDiagramId/withoutCiClass")
    @ModDesc(desc = "根据视图历史版本ID查询CI数据", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult getHistroyCIInfoByDiagramIdWithoutCiClass(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        List<CcCiInfo> data = bmDiagramPeer.getHistroyCIInfoByDiagramIdWithoutCiClass(diagramDTO.getDiagramId(), diagramDTO.getSheetId());
        return new RemoteResult(data);
    }


    @RequestMapping("/getHistroyRltInfoByDiagramId")
    @ModDesc(desc = "根据视图历史版本ID查询RLT数据", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult getHistroyRltInfoByDiagramId(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        List<EamCiRltDTO> data = bmDiagramPeer.getHistroyRltInfoByDiagramId(diagramDTO.getDiagramId(), diagramDTO.getSheetId());
        return new RemoteResult(data);
    }

    @RequestMapping("/getHistroyRltInfoByDiagramId/withoutCi")
    @ModDesc(desc = "根据视图历史版本ID查询RLT数据--不包含CI数据", pDesc = "条件", pType = String.class, pcType = ESCISearchBean.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult getHistroyRltInfoByDiagramIdWithoutCI(@RequestBody ReleaseModuleDiagramDTO diagramDTO) {
        List<EamCiRltDTO> data = bmDiagramPeer.getHistroyRltInfoByDiagramIdWithoutCI(diagramDTO.getDiagramId(), diagramDTO.getSheetId());
        return new RemoteResult(data);
    }

    @RequestMapping("/getRulesByStep")
    @ModDesc(desc = "根据步骤获取规则", pDesc = "条件", pType = QuickDrawingDto.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult getRulesByStep(@RequestBody QuickDrawingDto drawingDto) {
        if(BinaryUtils.isEmpty(drawingDto.getDiagramId()) || BinaryUtils.isEmpty(drawingDto.getCiCode())){
            return new RemoteResult(Collections.emptyList());
        }
        List<CcCiInfo> data = bmDiagramPeer.getRulesByStep(drawingDto);
        return new RemoteResult(data);
    }

    @RequestMapping("/queryHistoryDiagramInfoByIds")
    @ModDesc(desc = "根据视图ID和版本号查询对应的历史版本视图信息 --- 支持批量", pDesc = "条件", pType = QuickDrawingDto.class, rDesc = "对象数据", rType = List.class)
    public RemoteResult queryHistoryDiagramInfoByIds(@RequestBody List<ReleaseModuleDiagramDTO> releaseModuleDiagramDTOs) {
        Map<String,List<EamReleaseHistoryDTO>> data = bmDiagramPeer.queryHistoryDiagramInfoByIds(releaseModuleDiagramDTOs);
        return new RemoteResult(data);
    }

}
